package com.qf.ability.message.handler;

import com.alibaba.fastjson.JSON;
import com.qf.ability.message.entity.Message;
import com.qf.ability.message.entity.Room;
import com.qf.ability.message.entity.UserSession;
import com.qf.ability.message.handler.base.BaseInChannelHandler;
import com.qf.ability.message.utils.RoomUtils;
import com.qf.commons.core.utils.JwtUtils;
import com.qf.data.user.entity.Teacher;
import com.qf.data.user.entity.WxUser;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 初始化连接事件
 * author Ken
 * create_time 2022/10/17
 */
@Component
@Slf4j
@ChannelHandler.Sharable
public class ConnMsgInChannelHandler extends BaseInChannelHandler<Message> {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    protected boolean isSupport(Message msg) {
        return msg.getId().equals("conn");
    }

    @Override
    protected void hander(ChannelHandlerContext ctx, Message msg) {
        //获得课程id 通过课程id 获取当前正在上课的章节名称和id
        Integer cid = msg.getCid();
        String descId = (String) redisTemplate.opsForHash().get("course_" + cid,"desc_id");
        String title = (String) redisTemplate.opsForHash().get("course_" + cid, "desc_title");

        //获取用户令牌并且解析
        String token = msg.getToken();
        String userJson = JwtUtils.parseJwtToken(token, "user");
        log.debug("[conn] 令牌解析的结果 - {}", userJson);

        if (userJson == null) {
            Message message = new Message()
                    .setId("tokenError");
            ctx.channel().writeAndFlush(message);
            return;
        }

        Integer id = null;
        String name = null;
        String header = null;

        //获取是主播 还是 观看者
        String role = msg.getRole();
        if (role.equals("master")) {
            Teacher teacher = JSON.parseObject(userJson, Teacher.class);
            name = teacher.getName();
            header = teacher.getHeader();
            id = teacher.getId();
        } else {
            WxUser wxUser = JSON.parseObject(userJson, WxUser.class);
            name = wxUser.getNickname();
            header = wxUser.getHeader();
            id = wxUser.getId();
        }

        //创建一个用户会话对象
        UserSession userSession = new UserSession()
                .setUid(id)
                .setRole(role)
                .setNickname(name)
                .setHeader(header)
                .setChannel(ctx.channel());

        //获得房间
        Room room = RoomUtils.get(cid);
        room.addUser(userSession);

        //如果是观看者上线 则更新在线人数
        if (userSession.getRole().equals("slave")) {
            //添加在线人数
            Long onlineCount = redisTemplate.opsForHash().increment("course_" + cid, "online_count", 1);

            //通知给房间其他人的消息
            Message message = new Message()
                    .setId("onlineResult")
                    .setContent(onlineCount);
            room.sendAll(message, true);
        }

        //返回给客户端
        Map<String, Object> datas = new HashMap<>();
        datas.put("uid", userSession.getUid());
        datas.put("title", title);
        datas.put("descId", descId);
        datas.put("isPlayer", room.isPlayer());
        Message message = new Message().setId("connResult").setContent(datas);

        ctx.channel().writeAndFlush(message);
    }
}
